<?php
namespace app\zhongkl_forum\controller;
use think\facade\Db; 
use think\facade\Filesystem;
use think\Config; 
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\zhongkl_forum\model\Test ;
use think\Request;
use \topthink\Captcha;
class Answer  extends Controller
{
    use \liliuwei\think\Jump;
    public function code(){
        return $this->fetch('code');
    }
    public function index(){
        // 查询表zhongkl_paper信息
        $paper = DB::table('zhongkl_paper')
            ->field('p_id,p_name,p_time')
            ->select();
        return view('',['paper' => $paper]);
    }
    // 考试试题
    public function exam(){
        // 获取url传递的p_id,根据p_id查询所需要的试卷试题q_id
        // 存储p_id相关的试题
        $exam = DB::table('zhongkl_exam')
            ->field('q_id,p_id,q_name,A,B,C,D,E,F')
            ->where('p_id',input('p_id'))
            ->select();
        // 判断当前试卷是否有试题，解决无试题导致的 未定义数组下标: 0 错误
        if(count($exam)>0){
            return view('',['exam' => $exam,'p_id' => input('p_id')]);
        }else{
            $this->error("该试卷尚未可答试题");
        }
    }
    // 考试结果
    public function doExam(){
        // 变量post存储前端传递的答案
        $post = $_POST;
        // 存储回答答案
        $string = [];
        // correct存储回答正确的题目p_id
        $correct = [];
        // wrong存储回答错误的题目p_id
        $wrong = [];
        $exam = DB::table('zhongkl_exam')
            ->field('q_id,q_answer')
            ->where('p_id',input('p_id'))
            ->select();
        foreach($post as $key => $a){
            foreach($exam as $key1 => $b){
                if($exam[$key1]['q_id'] == $key){
                    if($exam[$key1]['q_answer'] == $post[$key][0]){
                        $correct[] = $key;
                    }else{
                        $wrong[] = $key;
                    }
                    $string[]=  implode('-',[$key,$a[0]]);
                }else{
                    continue;
                }
            }
        }
        // 将数组中的答案转换为字符串
        $str = '';
        $str = implode(',',$string);
        $correct = implode(',',$correct);
        $wrong = implode(',',$wrong);
        // 准备录入score
        $score = [
            "s_Sname"   => "暂无名字",
            "p_id"      => input('p_id'),
            "s_answer"  => $str,
            "correct"   => $correct,
            "wrong"     => $wrong
        ];
        if($score >0){
            $Score = DB::connect("mysql123")
                ->table('zhongkl_score')
                ->insert($score);
            $this->success("成绩录入成功",url("Answer/score",["p_id" => input("p_id")]));
        }else{
            $this->error("成绩录入失败，原因是：没有可录入的成绩，请检查你所提交的答案");
        }
        
    }
    // 成绩查询
    public function score(){
        // 多表查询paper和score 得到考试结果信息 存储与$score
        $score = DB::view('zhongkl_paper','p_id,p_name')
            ->view('zhongkl_score','s_Sname,p_id','zhongkl_paper.p_id = zhongkl_score.p_id and s_Sname = "暂无名字"')
            ->order('s_time','desc')
            ->select();
        $newScore=[];
        for($i=0;$i<count($score);$i++){
            $id = $score[$i]['p_id'];
            if($i == 0){
                array_unshift($newScore,$score[$i]);
                continue;
            }
            for($j=0;$j<count($newScore);$j++){
                if($id != $newScore[$j]['p_id'] && $j == count($newScore)-1){
                    array_push($newScore,$score[$i]);
                }else break;
            }
        }
        return view('',['score' => $newScore]);
    }
    public function doScore(){
        $score = DB::table('zhongkl_score')
            ->field('s_id,p_id,s_time')
            ->where('zhongkl_score.p_id',input('p_id'))
            ->order('s_time','desc')
            ->select();
        return view('',['score'=>$score]);
    }
    public function errorTest(){
        $paperName = DB::table('zhongkl_paper')
            ->field('p_name')
            ->where('p_id',input('p_id'))
            ->find();
        $exam = DB::view('zhongkl_note','n_note,q_id')
            ->view('zhongkl_exam','q_name,q_id,p_id,q_answer,A,B,C,D,E,F','zhongkl_note.q_id = zhongkl_exam.q_id','RIGHT')
            ->where('p_id',input('p_id'))
            ->order('q_id')
            ->select();
        $score = DB::table('zhongkl_score')
            ->where('s_id',input('s_id'))
            ->find();
        $score = explode(',',$score['s_answer']);
        foreach($score as $key =>$value){
            $scoreNum = explode('-',$score[$key]);
            $score[$key] = $scoreNum[1];
        }
        for($i = 0 ;$i<count($exam);$i++){
            $a=array('s_answer' => $score[$i]);
            $ex[] =(array)$exam[$i];
            $ex[$i] += $a;
        }
        return view('',['paperName'=>$paperName,'ex'=>$ex]);
    }
    // 添加笔记
    public function note(){
        $number = DB::connect('mysql123')
            ->table('zhongkl_note')
            ->where('q_id',input('q_id'));
        // 接受隐藏inpout传值，判断要进行什么操作
        $button = input('button');
        // 接受传值noteText,判断是否需要添加的笔记
        $noteText = input('noteText');
        // oldNote
        $oldNote = DB::table('zhongkl_note')
                ->field('n_note')
                ->where('q_id',input('q_id'))
                ->find();
        if($noteText){
            // 存在传值noteText
            if($button == "add" && $oldNote){
                // button传值是add操作且存在旧笔记时
                // 执行添加操作 笔记为就笔记+新笔记
                // 执行操作为update
                $newNote = ['n_note' => $oldNote['n_note'].$noteText];
                $note = $number->update($newNote);
            }elseif($button == "add" && !$oldNote){
                // button传值是add操作且不存在旧笔记时
                // 笔记内容为传值$onteText
                // 执行操作为insert
                $newNote = ['n_note' => $noteText];
                $newNote = [
                        'q_id' => input('q_id'),
                        'n_note' => $noteText
                    ];
                $note = DB::connect('mysql123')
                    ->table('zhongkl_note')
                    ->insert($newNote);
            }elseif($button == "update"){
                // button传值是update操作
                // 执行更新操作
                $note = $number->update(['n_note' => $noteText ]);
            }elseif($button == "del"){
                // button传值是del操作
                // 执行delete操作 
                $note = $number->delete();
            }else{
                $this->error('出现了意外的事情');
            }
        }else{
            // 无笔记传值内容，buuton的值为del
            // 执行delete操作
            if($button == "del"){
                $note = $number->delete();
            }else{
                $this->error('出现了意外的事情');
            }
        }
        // 判断存在有无对数据库的操作
        if($note){
            // 存在
            $this->success($button."成功",'Answer/score');
        }else{
            // 不存在
            $this->error('失败');
        }
        //     ->insert($noto);
        // if($number){
        //     redirect()->restore();
        // }
    }
    // 发布试题
    public function lssue(){
        $paper = DB::table('zhongkl_paper')
            ->field('p_name,p_id')
            ->order('p_time','desc')
            ->select();
        return view('',['paper'=>$paper]);
    }
    public function doLssue(){
        // 判断是否存在传值
        if(input('paperName')){
            // 判断试卷是否已经存在
            $p_id = DB::table('zhongkl_paper')
                ->field('p_id')
                ->where('p_id',input('paperName'))
                ->find();
            if($p_id){
                //存在 保存到$p_id
                $pid = input('paperName');
            }else{
                // 不存在
                // 创建试卷二维数组
                $paper =  [
                    'p_name' => input('paperName'),
                    'p_tname' =>"万物"
                ];
                // 添加到数据表zhongkl_paper
                $paperNb = Db::connect("mysql123")
                    ->table('zhongkl_paper')
                    ->insert($paper);
                // 判断创建成功或失败
                if($paperNb){
                    //成功 获得试卷对应的p_id并保存到$p_id
                    $pid = DB::table('zhongkl_paper')
                            ->where('p_name',input('paperName'))
                            ->field('p_id')
                            ->find();
                    $pid = $pid['p_id'];
                }else{
                    //失败
                    $this->error('创建试卷失败，请重新创建或联系管理员','answer/lssue');
                }
            }
        }
        // $file存储上传的文件
        $file = request()->file('fileName');
        // 判断是否有文件上传
        if($file){
            // 上传文件
            $info = Filesystem::disk('public')->putFile('upload',$file);
            // 获得文件上传后的存放地址
            $fileName = "static\zhongkl_forum\\".$info;
            $ext = substr($fileName,strripos($fileName,'.'));
        }else{
            $this->error('未找到上传文件，请重新上传');
        }
        /*
            从文件中读取并上传试题
            1、获取文件的后缀
            2、根据不同的后缀加载不同的excel读取引擎
            3、定位工作表
            4、读取行和列记录构造数据入库的数组
            5、数据批量插入数据库
            路径：D:\AppServ\www\1803010144\public\static\zhongkl_forum\
        */
        // ext截取后缀用于判断文件类型
        if($ext == '.xlsx'){
            // 加载excel 2007 文件引擎
            $reader = IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);
            $spreadSheet = $reader->load($fileName);
            $workSheet = $spreadSheet->getActiveSheet();
            $datasheet = [];
            foreach($workSheet->getRowIterator() as $key =>$row){
                if($key > 1){
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false);
                    foreach($cellIterator as $k => $cell){
                        if( $k != 'A'){
                            $datasheet[$key][$k]=$cell->getValue();
                        }
                    }
                } 
            }
            $i = ['B','C','D','E','F','G','H','I'];
            foreach($datasheet as $key => $value){
                $table = [
                    'p_id' => $pid,
                    'q_answer' => $datasheet[$key][$i[0]],
                    'q_name'    => $datasheet[$key][$i[1]],
                    'A'    => $datasheet[$key][$i[2]],
                    'B'    => $datasheet[$key][$i[3]],
                    'C'    => $datasheet[$key][$i[4]],
                    'D'    => $datasheet[$key][$i[5]],
                    'E'    => $datasheet[$key][$i[6]],
                    'F'    => $datasheet[$key][$i[7]]
                ];
                $NUM = Db::connect("mysql123")
                ->table('zhongkl_exam')
                ->insert($table);
            }
            // 
            if($NUM){
                $this->success('添加试题成功','answer/lssue');
            }else{
                $this->error('添加失败');
            }
            
        }elseif($ext == '.xls'){
            // 加载excel 2003文件引擎
        }else{

            $this->error("你要加载的文件格式识别失败");
        }
        
    }
    public function suanfa(){
        $str = "open_door";
        $str_arr = explode("_",$str);
        $str_implode = implode("",$str_arr);
        var_dump($str_arr,ucwords($str_implode));
        $string = [1,2,3,45,5];
        print_r(strlen($string));
    }
}